package com.nami.gate.router;

import com.nami.gate.router.config.GateConfig;
import com.nami.gate.router.config.NacosConfig;
import com.nami.gate.router.constants.CommonConst;
import com.nami.gate.router.middleware.mq.MqConsumer;
import com.nami.gate.router.middleware.mq.MqSender;
import com.nami.gate.router.middleware.mq.consumer.RocketMqConsumerImpl;
import com.nami.gate.router.middleware.mq.producer.RocketMqSenderImpl;
import com.nami.gate.router.register.RegisterService;
import com.nami.gate.router.register.impl.NacosRegisterServiceImpl;
import com.nami.gate.router.register.request.RegisterRequest;

public class RouterController {

    private GateConfig config;

    public RouterController(GateConfig config) {
        this.config = config;
    }

    public static MqSender sender;
    public static MqConsumer consumer;
    public static RegisterService registerService;

    public void start() throws Exception {

        // 将netty服务 注册到注册中心
        if (CommonConst.NACOS.equals(config.getRegisterType())) {
            RegisterRequest request = new RegisterRequest();
            NacosConfig nacosConfig = config.getNacosConfig();
            request.setServerAddr(nacosConfig.getServerAddr());
            request.setUsername(nacosConfig.getUsername());
            request.setPassword(nacosConfig.getPassword());
            request.setNamespace(nacosConfig.getNamespace());

            request.setIp(config.getIp());
            request.setPort(config.getGatePort());
            registerService = new NacosRegisterServiceImpl();
            registerService.start(request);
        }
        sender = new RocketMqSenderImpl(config.getRocketMqConfig());
        sender.start();

        consumer = new RocketMqConsumerImpl(config.getRocketMqConfig(), sender);
        consumer.start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            RouterController.this.shutdown();
        }));

    }


    public void shutdown() {
        registerService.shutdown();

        consumer.shutdown();

        sender.shutdown();
    }


}
